<?
	header('Content-Type: application/octet-stream');
	header('Content-Disposition: attachment; filename="revenue-'.date("Y-m-d").'.csv"');
	header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
	
	include("../../functions.inc.php");

	if($_GET['SFrom']) $SFrom=$_GET['SFrom'];
	elseif ($_POST['SFrom']) $SFrom=$_POST['SFrom'];
	if($_GET['SText']) $SText=$_GET['SText'];
	elseif ($_POST['STo']) $STo=$_POST['STo'];
	if($_GET['STo']) $STo=$_GET['STo'];
	elseif ($_POST['SText']) $SText=$_POST['SText'];
	if($_GET['SType']) $SType=$_GET['SType'];
	elseif ($_POST['SType']) $SType=$_POST['SType'];
	if($_GET['RType']) $RType=$_GET['RType'];
	elseif ($_POST['RType']) $RType=$_POST['RType'];
	else $RType="All";
	if($_GET['OType']) $OType=$_GET['OType'];
	elseif ($_POST['OType']) $OType=$_POST['OType'];
	else $OType="guestName";
	
	
	if(!empty($SFrom)&&!empty($STo)){
		$SearchSQL.=" AND (bookingDate>='".SwapDates($SFrom)."' AND bookingDate<='".SwapDates($STo)." 23:59:59') ";
	}
	if(!empty($_GET['Affs'])){
		$_POST['affiliates']=split(",",$_GET['Affs']);
		$SearchSQL.=" AND affiliateID IN (";
		$First=true;
		foreach($_POST['affiliates'] as $val){
			if(!$First){
				$SearchSQL.=",";
				$Affs.=",";
			}
			$SearchSQL.=$val;
			$Affs.=$val;
			$First=false;
		}
		$SearchSQL.=") ";
	}
	
	$SQL2="SELECT DATE_FORMAT(bookingDate,'%a %e %b %Y') AS BookingDate,confnum,guestName,contactName,((price*amount)+bookingfee) AS Amount,affiliateCommission FROM bookings,affiliate WHERE  affiliateID=affiliate.id  $SearchSQL  ORDER BY $OType ";
	
	include("../../classes/clsDB.php");
	$FirstRow=true;
	$FirstRowText="";
	$r=new ReturnRecord();
	$sq2=$r->rawQuery($SQL2);  
	while ($myrow = mysql_fetch_assoc($sq2)) {
		$FirstColumn=true;
		$RowText="";
		foreach($myrow as $key=>$val){
			$seperator=($FirstColumn ? "" : ",");
			if($FirstRow){
				$FirstRowText.=$seperator.$key;
			}
			$RowText.=$seperator.(eregi(",",$val) ? '"'.$val.'"' : $val);
			$FirstColumn=false;
		}
		if($FirstRow){
			$RowText=$FirstRowText."\n".$RowText."\n";
		}else{
			$RowText.="\n";
		}
		
		print $RowText;
		
		$FirstRow=false;
	};
?>